package com.lhn.netty.netty_demo.group_chat;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 客户端
 *
 * @author lhn
 * @date 2025/06/03 16:20
 * @since 1.0.0
 **/
public class GroupChatClient {

    // 属性
    private String host;
    private int port;

    // 构造器
    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        // 创建客户端启动对象
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors) // 添加线程组
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer <SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            // 加入自定义的handler
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    })
            ;
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            Channel channel = channelFuture.channel();
            System.out.println(channel.localAddress() + "客户端 ok...");
            // 客户端需要输入信息, 创建一个扫描器
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                // 通过channel 发送数据
                channel.writeAndFlush(msg + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                eventExecutors.shutdownGracefully();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1", 17000).run();
    }

}